package xprom

import (
	"gitee.com/igolang/pkg/xhttp"
	"gitee.com/igolang/pkg/xjson"
	"net/http"

	"github.com/prometheus/client_golang/prometheus"
)

type renderJSON struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data"`
}

// JSONHandler 在使用次方法前，请先调用 promhttp.Handler()
func JSONHandler() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		mfs, err := prometheus.DefaultGatherer.Gather()
		var data renderJSON
		if err != nil {
			data = renderJSON{
				Code:    http.StatusInternalServerError,
				Message: err.Error(),
				Data: struct {
				}{},
			}
			writerJSON(w, http.StatusInternalServerError, data)
			return
		}
		result := make([]*Family, len(mfs))
		for i, mf := range mfs {
			result[i] = NewFamily(mf)
		}
		data = renderJSON{
			Code:    0,
			Message: "ok",
			Data:    result,
		}
		writerJSON(w, http.StatusOK, data)
	})
}

func writerJSON(w http.ResponseWriter, code int, data interface{}) {
	w.Header().Set(xhttp.HeaderContentType, xhttp.MIMEApplicationJSONCharsetUTF8)
	w.WriteHeader(code)
	b, err := xjson.Marshal(data)
	if err != nil {
		panic(err)
	}
	_, err = w.Write(b)
	if err != nil {
		panic(err)
	}
}
